<!--#layout name=mail-->
<div id="app">
  <div class="block-email">
    <div class="email-panel">
      <div class="email-panel-header">
        <div class="btn-group btn-checkbox">
          <a
            href="javascript:;"
            data-toggle="dropdown"
            class="btn btn-default btn-xs dropdown-toggle"
          >
            <input type="checkbox" /><i class="fa fa-angle-down"></i>
          </a>
          <ul class="dropdown-menu">
            <li
              v-for="($data,index) in checkTypes"
              :key="index"
              @click="onCheckType($data.value)"
            >
              <a href="javascript:;">{{ $data.displayName}}</a>
            </li>
          </ul>
        </div>
        <div class="btn-group">
          <button
            class="btn btn-default btn-xs dropdown-toggle"
            data-toggle="dropdown"
            ><span>Action</span> <i class="fa fa-angle-down"></i
          ></button>
          <ul class="dropdown-menu">
            <li
              v-for="($data,index) in actions"
              @click="onAction($data.value)"
              :class="{disabled: !selectedList.length}"
            >
              <a href="javascript:;">{{$data.displayText}}</a>
            </li>
          </ul>
        </div>
        <button
          class="btn btn-default btn-xs pull-right"
          title="Refresh"
          @click="refreshList"
          ><i class="fa fa-refresh"></i
        ></button>
      </div>
      <div class="list-group">
        <a
          v-for="mail in mailList"
          :key="mail.id"
          @click="selectMail(mail)"
          :class="{ active: mail.id==(currentMail||{}).id, highlight: !mail.read }"
          href="javascript:;"
          class="list-group-item"
        >
          <input
            type="checkbox"
            :checked="selectedList.indexOf(mail)>-1"
            @click.stop="checkMail(mail)"
            class="meta"
          />
          <i v-if="mail.hasAttachment" class="meta fa fa-paperclip"></i>
          <span class="meta data">{{mail.displayDate}}</span>
          <h4 class="list-group-item-heading"
            >{{mail.subject || '(' + Kooboo.text.mail.noSubject + ')'}}</h4
          >
          <p class="list-group-item-text nowrap-text">{{ mail.from}}</p>
        </a>
        <a
          href="javascript:;"
          @click="loadMore"
          class="list-group-item action text-center"
          >More...</a
        >
      </div>
    </div>
    <div v-if="currentMail" class="email-wrapper">
      <div class="email-wrapper-toolbar">
        <div class="btn-group pull-left">
          <a @click="onReply" class="btn btn-xs blue"
            ><i class="fa fa-reply"></i> <span>Reply</span></a
          >
          <button data-toggle="dropdown" class="btn btn-xs blue dropdown-toggle"
            ><i class="fa fa-angle-down"></i
          ></button>
          <ul class="dropdown-menu">
            <li @click="onForward">
              <a href="javascript:;">Forward</a>
            </li>
            <li @click="onPrint">
              <a href="javascript:;">Print</a>
            </li>
            <li class="divider"></li>
            <li @click="moveToFolder('Inbox')">
              <a href="javascript:;">Not Spam</a>
            </li>
            <li @click="moveToFolder('Trash')">
              <a href="javascript:;">Delete</a>
            </li>
          </ul>
        </div>
        <div class="btn-group pull-right">
          <a
            href="javascript:;"
            @click="showPrevMail"
            class="btn btn-xs btn-default"
            ><i class="fa fa-fw fa-angle-left"></i
          ></a>
          <a
            href="javascript:;"
            @click="showNextMail"
            class="btn btn-xs btn-default"
            ><i class="fa fa-fw fa-angle-right"></i
          ></a>
        </div>
      </div>
      <div class="email-wrapper-content">
        <div class="email-wrapper-header">
          <h4 class="title"
            >{{ currentMail.subject || '(' + Kooboo.text.mail.noSubject +
            ')'}}</h4
          >
          <table>
            <tr>
              <th><span>From</span>:</th>
              <td>
                <strong>{{currentMail.from.name}}</strong>
                {{'<' + currentMail.from.address + '>'}}
              </td>
            </tr>
            <tr>
              <th><span>MAIL_TO</span>:</th>
              <td>
                <template v-for="($data,index) in currentMail.to">
                  <strong :key="index">{{$data.name}}</strong>
                  {{'<' + $data.address + '>'}}
                  <template v-if="currentMail.to.length - 1 !== index">
                    ,
                  </template>
                </template>
              </td>
            </tr>
            <tr v-if="currentMail.cc.length">
              <th><span>Cc</span>:</th>
              <td>
                <template v-for="($data,index) in currentMail.cc">
                  <strong :key="index">{{$data.name}}</strong>
                  {{'<' + $data.address + '>'}}
                  <template v-if="currentMail.cc.length - 1 !== index">
                    ,
                  </template>
                </template>
              </td>
            </tr>
            <tr v-if="currentMail.bcc.length">
              <th><span>Bcc</span>:</th>
              <td v-for="($data,index) in currentMail.bcc">
                <strong :key="index">{{$data.name}}</strong>
                {{'<' + $data.address + '>'}}
                <template v-if="currentMail.bcc.length - 1 !== index">
                  ,
                </template>
              </td>
            </tr>
            <tr>
              <th><span>Date</span>:</th>
              <td>
                <strong>
                  {{new Date(currentMail.date).toDefaultLangString()}}
                </strong>
              </td>
            </tr>
          </table>

          <table v-if="currentMail.attachments.length">
            <tr>
              <th>
                <i class="meta fa fa-paperclip"></i>
                {{currentMail.attachments.length +
                Kooboo.text.mail.attachments}} :
              </th>
              <td>
                <template v-for="($data,index) in currentMail.attachments">
                  <a
                    :key="index"
                    href="javascript:;"
                    @click="downloadAttachment($data)"
                    >{{$data.fileName}}</a
                  >
                  <template v-if="currentMail.attachments.length - 1 !== index">
                    ,
                  </template>
                </template>
                |
                <strong
                  ><a href="" @click="downloadAttachment(null)"
                    >Download all</a
                  ></strong
                >
              </td>
            </tr>
          </table>
        </div>
        <iframe src="about:blank" class="auto-height"></iframe>
      </div>
    </div>
  </div>
  <div
    class="modal fade"
    data-backdrop="static"
    data-keyboard="false"
    v-kb-modal="showMoveModal"
  >
    <div class="modal-dialog" v-if="showMoveModal">
      <div class="modal-content">
        <div class="modal-header">
          <button data-dismiss="modal" class="close"
            ><i class="fa fa-close"></i
          ></button>
          <h4 class="modal-title">Move to</h4>
        </div>
        <div class="modal-body">
          <div class="note note-info">
            <p>The selected messages will be moved</p>

            <dl>
              <template v-for="($data,index) in selectedList">
                <dt :key="index">{{$data.subject}}</dt>
                <dd>
                  {{new Date($data.date).toDefaultLangString()}}
                </dd>
              </template>
            </dl>
          </div>
          <div class="form-horizontal">
            <div class="form-group">
              <label class="control-label col-md-2">Move to</label>
              <div class="col-md-10">
                <select v-model="targetFolder" class="form-control">
                  <option
                    v-for="item in folders"
                    :key="item.value"
                    :value="item.value"
                    >{{item.displayName}}</option
                  >
                </select>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="startMove" class="btn green">Save</button>
          <button data-dismiss="modal" class="btn gray">Cancel</button>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
  var self = new Vue({
    el: "#app",
    data: function() {
      return {
        checkTypes: [
          {
            displayName: Kooboo.text.common.all,
            value: "All"
          },
          {
            displayName: Kooboo.text.mail.read,
            value: "Read"
          },
          {
            displayName: Kooboo.text.mail.unread,
            value: "Unread"
          }
        ],
        actions: [
          {
            displayText: Kooboo.text.common.delete,
            value: "delete"
          },
          {
            displayText: Kooboo.text.mail.moveTo,
            value: "move"
          },
          {
            displayText: Kooboo.text.mail.markAsRead,
            value: "read"
          },
          {
            displayText: Kooboo.text.mail.markAsUnread,
            value: "unread"
          }
        ],
        selectedList: [],
        mailList: [],
        currentMail: null,
        showMoveModal: false,
        receptAddress: "",
        folders: [
          {
            displayName: Kooboo.text.mail.Inbox,
            value: "Inbox"
          },
          {
            displayName: Kooboo.text.mail.Sent,
            value: "Sent"
          }
        ],
        targetFolder: "Inbox"
      };
    },
    mounted: function() {
      var self = this;
      self.refreshList();
    },
    methods: {
      onCheckType: function(type) {
        switch (type) {
          case "All":
            self.selectedList = self.mailList;
            break;
          case "Read":
            _.forEach(self.mailList, function(mail) {
              self.selectedList = self.mailList.filter(function(f) {
                return f.read;
              });
            });
            break;
          case "Unread":
            _.forEach(self.mailList, function(mail) {
              self.selectedList = self.mailList.filter(function(f) {
                return !f.read;
              });
            });
            break;
        }
      },
      onAction: function(type) {
        if (self.selectedList.length) {
          switch (type) {
            case "delete":
              var _ids = self.selectedList.map(function(mail) {
                return mail.id;
              });

              Kooboo.EmailMessage.Moves({
                ids: JSON.stringify(_ids),
                folder: "Trash"
              }).then(function(res) {
                if (res.success) {
                  if (self.selectedList.indexOf(self.currentMail) > -1) {
                    self.currentMail == null;
                  }

                  self.mailList = self.mailList.filter(function(f) {
                    return _ids.indexOf(f.id) == -1;
                  });
                  self.selectedList = [];

                  window.info.show(Kooboo.text.info.moveTo.Trash.success, true);
                } else {
                  window.info.show(Kooboo.text.info.moveTo.Trash.fail, false);
                }
              });
              break;
            case "move":
              self.showMoveModal = true;
              break;
            case "read":
            case "unread":
              var _ids = self.selectedList.map(function(mail) {
                return mail.id;
              });

              var state = type == "read";
              Kooboo.EmailMessage.MarkReads({
                ids: JSON.stringify(_ids),
                value: state
              }).then(function(res) {
                if (res.success) {
                  self.selectedList.forEach(function(f) {
                    f.read = state;
                  });
                  self.selectedList = [];
                }
              });
              break;
          }
        }
      },
      refreshList: function() {
        Kooboo.EmailMessage.getList({
          folder: "Spam",
          address: Kooboo.getQueryString("address") || ""
        }).then(function(res) {
          if (res.success) {
            self.mailList = res.model;
            self.selectedList = [];
            self.currentMail = null;
          }
        });
      },
      selectMail: function(m) {
        if (m) {
          self.receptAddress = m.rcptTo;
          Kooboo.EmailMessage.getContent({
            messageId: m.id
          }).then(function(res) {
            if (res.success) {
              m.read = true;
              self.currentMail = res.model;
              location.hash = "";
            }
          });
        } else {
          self.currentMail = null;
        }
      },
      loadMore: function() {
        if (self.mailList.length) {
          Kooboo.EmailMessage.More({
            folder: "Spam",
            address: Kooboo.getQueryString("address") || "",
            messageId: self.mailList[self.mailList.length - 1].id
          }).then(function(res) {
            if (res.success) {
              res.model.forEach(function(f) {
                if (
                  self.mailList.every(function(s) {
                   return s.id != f.id;
                  })
                ) {
                  self.mailList.push(f);
                }
              });
            }
          });
        }
      },
      checkMail: function(data) {
        var mail = self.selectedList.find(function(f) {
          return f.id == data.id;
        });
        if (mail) {
          self.selectedList =
            self.selectedList.filter(function(f) {
              return f != mail;
            });
        } else {
          self.selectedList.push(data);
        }
      },
      onReply: function() {
        location.href = Kooboo.Route.Get(Kooboo.Route.Email.Compose, {
          type: "Reply",
          sourceId: self.currentMail.id,
          from: self.receptAddress,
          folder: "Spam"
        });
      },
      onForward: function() {
        location.href = Kooboo.Route.Get(Kooboo.Route.Email.Compose, {
          type: "Forward",
          sourceId: self.currentMail.id,
          from: self.receptAddress,
          folder: "Spam"
        });
      },
      moveToFolder: function(folder) {
        Kooboo.EmailMessage.Moves({
          ids: JSON.stringify([self.currentMail.id]),
          folder: folder
        }).then(function(res) {
          if (res.success) {
            self.mailList = self.mailList.filter(function(f) {
              return f.id != self.currentMail.id;
            });
            self.selectMail(self.mailList[0]);
            window.info.show(Kooboo.text.info.moveTo[folder].success, true);
          } else {
            window.info.show(Kooboo.text.info.moveTo[folder].fail, false);
          }
        });
      },
      showPrevMail: function() {
        var idx = _.findIndex(self.mailList, function(mail) {
          return mail.id == self.currentMail.id;
        });

        if (idx !== 0) {
          self.selectMail(self.mailList[idx - 1]);
        }
      },
      showNextMail: function() {
        var idx = _.findIndex(self.mailList, function(mail) {
          return mail.id == self.currentMail.id;
        });
        if (idx !== self.mailList.length - 1) {
          self.selectMail(self.mailList[idx + 1]);
        }
      },
      downloadAttachment: function(attachment) {
        window.open(
          Kooboo.EmailAttachment.downloadAttachment() +
            "/" +
            self.currentMail.id +
            (attachment ? "/" + attachment.fileName : "")
        );
      },
      onPrint: function() {
        window.open(
          Kooboo.Route.Get(Kooboo.Route.Email.PrintPage, {
            id: self.currentMail.id,
            folder: "Sent"
          })
        );
      },
      startMove: function() {
        var _ids = self.selectedList.map(function(mail) {
          return mail.id;
        });
        Kooboo.EmailMessage.Moves({
          ids: JSON.stringify(_ids),
          folder: self.targetFolder || "Inbox"
        }).then(function(res) {
          if (res.success) {
            self.mailList = self.mailList.filter(function(f) {
              return _ids.indexOf(f.id) == -1;
            });
            self.selectedList = [];
            self.selectMail(self.mailList[0]);
            self.showMoveModal = false;
            window.info.show(
              Kooboo.text.info.moveTo[self.targetFolder || "Inbox"].success,
              true
            );
          } else {
            window.info.show(
              Kooboo.text.info.moveTo[self.targetFolder || "Inbox"].fail,
              false
            );
          }
        });
      },
      adjustIframe: function() {
        $(iframe).removeAttr("style");
        $(iframe).height(iframe.contentWindow.document.body.scrollHeight + 20);
      }
    },
    watch: {
      currentMail: function(mail) {
        if (mail) {
          iframe = $("iframe.auto-height")[0];

          var setHTML = function(code) {
            iframe.contentWindow.document.documentElement.innerHTML = code;
            $("img", iframe.contentWindow.document)
              .load(function() {
                self.adjustIframe();
              })
              .error(function() {
                self.adjustIframe();
              });

            $("a", iframe.contentWindow.document).on("click", function(e) {
              e.preventDefault();
              parent.window.open($(this).attr("href"));
            });

            self.adjustIframe();
          };

          if (!iframe) {
            setTimeout(function() {
              iframe = $("iframe.auto-height")[0];
              setHTML(mail.html);
            }, 300);
          } else {
            setHTML(mail.html);
          }
        }
      }
    }
  });
</script>
